/**
 * Created by apple on 16/7/4.
 */
angular.module('starter.taskService', [])
  .service('$task', function ($dfUtil, $rootScope, $loading, $q, $dfHttp,$state,ROLES,$imageUploadCache,IMAGES,$cordovaFile,$interval) {

    function uploadImage(funName,funId,imageClass,invalidUuids,files) {
      var param = {
        'funName':funName,
        'funId':funId,
        'imageClass':imageClass,
        'invalidUuids':invalidUuids
      };
      return $dfHttp.postForm('api/file/uploadImages.json',param,files);
    }

    function uploadImageToServer(funId, funName, imageClass) {
      var deferred = $q.defer();
      var promise = deferred.promise;

      promise.success = function(fn){
        promise.then(fn);
        return promise;
      };

      promise.error = function(fn){
        promise.then(null,fn);
        return promise;
      };

      var photoDatasArray = [] ;
      var imageCache = $imageUploadCache.getImagesByParams(funId, funName, imageClass);

      if(!imageCache.images) {
        imageCache.images = [] ;
      }
      if(imageCache.images.length == 0) {
        deferred.resolve({code:'SUCCESS',msg:'没有图片,无需上传',data:{imageClass:imageClass,funId:funId,funName:funName}});
        return promise;
      }

      var count = 0;

      if(imageCache.imageStatus == 'SUBMIT'){
        //imageCache.imageStatus = 'UPLOADING';
        //$imageUploadCache.saveImages(imageCache);
      }else {
        deferred.resolve({code:'SUCCESS',msg:'没有图片,无需上传',data:{imageClass:imageClass,funId:funId,funName:funName}});
        return promise;
      }

      angular.forEach(imageCache.images,function(image){
        if(image.resource == 'NETWORK'){
          return ;
        }

        count++ ;
        var pickImage = image.imageUrl ;
        var lastIndexOfSlash = pickImage.lastIndexOf('/');
        var filePath = pickImage.substr(0, lastIndexOfSlash); //p
        var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);
        $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function(arrayBuffer) {
          var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
          photoDatasArray.push(base64String);
        }, function(error) {
          deferred.reject({code:'LOAD_FILE_ERROR',msg:'本地图片没有找到,请确认存在',data:{imageClass:imageClass,funId:funId,funName:funName}});
        });
      });

      if(count == 0) {
        deferred.resolve({code:'SUCCESS',msg:'没有图片,无需上传',data:{imageClass:imageClass,funId:funId,funName:funName}});
        return promise;
      }

      if(imageCache.imageStatus == 'SUBMIT'){
        imageCache.imageStatus = 'UPLOADING';
        $imageUploadCache.saveImages(imageCache);
      }else {
        deferred.resolve({code:'SUCCESS',msg:'没有图片,无需上传',data:{imageClass:imageClass,funId:funId,funName:funName}});
        return promise;
      }

      //检测图片是否读取完成
      var fileloadTimer = $interval(function(e){
        if(photoDatasArray.length == count){

          //如果图片在上传中...跳过

          uploadImage('PROJECT',funId,imageCache.imageClass,imageCache.invalidUuids,photoDatasArray)
            .success(function(data){
              if(data.code == 'SUCCESS'){
                deferred.resolve({code:'SUCCESS',msg:data.msg,data:{imageClass:imageClass,funId:funId,funName:funName}});
              }else{
                deferred.reject({code:'FAIL',msg:data.msg,data:{imageClass:imageClass,funId:funId,funName:funName}});
              }
            }).error(function(data){
            deferred.reject({code:'NETWORK_ERROR',msg:'网络请求链接错误',data:{imageClass:imageClass,funId:funId,funName:funName}});
          });
          $interval.cancel(fileloadTimer);
        }
      },200,10);
      return promise ;
    }

    return {
      getTaskList: function (userId,listType) {
        var param = {
          userId:userId,
          listType:listType
        }
        return $dfHttp.get("api/project/getProjectInfoList.json",param);
      },
      getCountOfTasks : function(userId) {
        $rootScope.countOfTasks = {
          tab1: 0,
          tab2: 0,
          tab3: 0,
          tab4: 0,
        }
        $dfHttp.get('api/others/getListSize.json', {userId: userId})
          .success(function(data){
            if (data.code == "SUCCESS") {
              $rootScope.countOfTasks.tab1 = data.data[0];
              $rootScope.countOfTasks.tab2 = data.data[1];
              $rootScope.countOfTasks.tab3 = data.data[2];
              $rootScope.countOfTasks.tab4 = data.data[3];
            } else {
              $loading.showError("网络出了一点小问题,请稍后再试");
            }
          })
          .error(function(e){
            $loading.showError("网络异常,请稍后再试");
          })
      },

      createProjectIntention: function (intention) {
        return $dfHttp.post('api/project/createOrUpdateProject.json',intention);
      },
      getProjectIntention: function(userId,projectId){
        var param = {
          userId:userId,
          projectId:projectId
        }
        return $dfHttp.get('api/project/getProjectInfo.json',param);
      },
      getSurveyInfo : function (userId,projectId) {
        var param = {
          userId:userId,
          projectId:projectId
        }
        return $dfHttp.get('api/survey/getSurvey.json',param);
      },
      getDesignInfo : function (userId,projectId) {
        var param = {
          userId:userId,
          projectId:projectId
        }
        return $dfHttp.get('api/survey/getSolution.json',param);
      },
      submitPosition : function (userId,projectId,longitude,latitude){
        var param = {
          userId:userId,
          projectId:projectId,
          longitude:longitude,
          latitude:latitude
        }
        return $dfHttp.post('api/project/UpdateCoordinate.json',param);
      },
      uploadImage : uploadImage,
      uploadImage2 : function (funName,funId,imageClass,files) {
        var param = {
          'funName':funName,
          'funId':funId,
          'imageClass':imageClass
        };
        return $dfHttp.postForm('api/file/uploadImages2.json',param,files);
      },
      showChoiceBtn : function (user) {
        if(!user || !user.RoleMember){
          return false;
        }
        var choiceShow = false ;
        var roles = ","+ROLES.spmsAdmin+","+ROLES.spmsHtJszlAdmin+","+ROLES.spmsHtXsAdmin+","
        var roleMember = user.RoleMember ;
        angular.forEach(roleMember,function(role){
          if(role.roleCode == ROLES.spmsAdmin || ROLES.spmsHtJszlAdmin == role.roleCode || ROLES.spmsHtXsAdmin == role.roleCode){
            choiceShow = true ;
          }
        })
        return choiceShow ;
      },
      showTaskBtn: function(roleMember,projectStatus,btnClass){
        var showBtn = false ;
        switch(btnClass){
          case 'XSGJ':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm) && projectStatus == 'FOLLOWING') {
                showBtn = true ;
              }
            });
            break;
          case 'FQKC':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm) && projectStatus == 'FOLLOWING') {
                showBtn = true ;
              }
            });
            break;
          case 'CKYX':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm)) {
                showBtn = true ;
              }
            });
            break;
          case 'CKXSGJ':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorTech) && projectStatus == 'INVESTIGATING') {
                showBtn = true ;
              }
            });
            break;
          case 'JRKC':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorTech) && projectStatus == 'INVESTIGATING') {
                showBtn = true ;
              }
            });
            break;
          case 'WCKC':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorTech) && projectStatus == 'INVESTIGATING') {
                showBtn = true ;
              }
            });
            break;
          case 'FASJ':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorTech) && projectStatus == 'INVESTIGATED') {
                showBtn = true ;
              }
            });
            break;
          case 'TJSH':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorTech) && projectStatus == 'INVESTIGATED') {
                showBtn = true ;
              }
            });
            break;
          case 'QXYX':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm) && projectStatus == 'FOLLOWING') {
                showBtn = true ;
              }
            });
            break;
          case 'SH':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'INSTALLING') {
                showBtn = true ;
              }
            });
            break;
          case 'FH':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorCgy) && (projectStatus == 'FOR_INSTALL')) {
                showBtn = true ;
              }
            });
            break;
          case 'XMZC':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'INSTALLING') {
                showBtn = true ;
              }
            });
            break;
          case 'JDBG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'INSTALLING') {
                showBtn = true ;
              }
            });
            break;
          case 'HTQD':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm) && projectStatus == 'PLAN_CHECKED') {
                showBtn = true ;
              }
            });
            break;
          case 'XMRZ':
            //angular.forEach(roleMember,function(role){
            //  if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'INSTALLING') {
            //    showBtn = true ;
            //  }
            //});
            showBtn = true ;
            break;
          case 'WGSPTG':
            angular.forEach(roleMember,function(role){
              if(projectStatus == 'PLAN_CHECKING') {
                showBtn = true ;
              }
            });
            break;
          case 'WGSPJJ':
            angular.forEach(roleMember,function(role){
              if(projectStatus == 'PLAN_CHECKING') {
                showBtn = true ;
              }
            });
            break;
          case 'YQZG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsApproversOver) && (projectStatus == 'INCORPORATED' || projectStatus == 'PROJECTCHANGEOVER')) {
                showBtn = true ;
              }
            });
            break;
          case 'GLBG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && (projectStatus == 'INSTALLING')) {
                showBtn = true ;
              }
            });
            break;
          case 'QDSG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsDistributorSm) && (projectStatus == 'CONSTRACT_SIGNED')) {
                showBtn = true ;
              }
            });

            break;
          case 'SHBG':
            angular.forEach(roleMember,function(role){
              if((projectStatus == 'INSTALLING')) {
                showBtn = true ;
              }
            });
            break;
          case 'BWYS':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'INSTALLED') {
                showBtn = true ;
              }
            });
            break;
          case 'TYWG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsApproversOver) && (projectStatus == 'INCORPORATED' || projectStatus == 'PROJECTCHANGEOVER')) {
                showBtn = true ;
              }
            });
            break;
          case 'FAZG':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsInstallerPm) && projectStatus == 'PROJECTCHANGE') {
                showBtn = true ;
              }
            });
            break;
          case 'LIST-DFP':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsAdmin || role.roleCode == ROLES.spmsHtJszlAdmin || role.roleCode == ROLES.spmsHtScAdmin || role.roleCode == ROLES.spmsHtXsAdmin)) {
                showBtn = true ;
              }
            });
            break;
          case 'LIST-DSH':
            angular.forEach(roleMember,function(role){
              if((role.roleCode == ROLES.spmsApproversAdmin || role.roleCode == ROLES.spmsApproversEc || role.roleCode == ROLES.spmsApproversHt || role.roleCode == ROLES.spmsApproversOver)) {
                showBtn = true ;
              }
            });
            break;
        }
        return showBtn;
      },
      changeStatus: function(userId,projectId,status){
        return $dfHttp.post('api/project/updateProjectStatus.json',{userId:userId,projectId:projectId,projectStatus:status});
      },
      cancelProject: function(userId,projectId,cancelReason){
        return $dfHttp.post('api/project/cancelProject.json',{userId:userId,projectId:projectId,cancelReason:cancelReason});
      },
      autocalSunHeightAngle: function(latitude,hourAngle) {
        var pi = Math.PI;
        var sunHeightAngle = Math.asin(Math.sin(latitude*pi/180)*Math.sin(-23.5*pi/180)+Math.cos(latitude*pi/180)*Math.cos(-23.5*pi/180)*Math.cos(hourAngle*pi/180));
        return sunHeightAngle;
      },
      autocalSunDirectionAngle: function(sunHeightAngle,hourAngle) {
        var pi = Math.PI;
        var sunDirectionAngle = Math.asin(Math.cos(-23.5*pi/180)*Math.sin(hourAngle*pi/180)/Math.cos(sunHeightAngle));
        return sunDirectionAngle;
      },
      autocalFrontSpacing: function(long,componentAngle,sunHeightAngle,sunDirectionAngle) {
        var pi = Math.PI;
        var frontSpacing = long*Math.sin(componentAngle*pi/180)*Math.cos(sunDirectionAngle)/Math.tan(sunHeightAngle);
        return frontSpacing;
      },
      autocalEastSpacing: function(long,componentAngle,sunHeightAngle,sunDirectionAngle) {
        var pi = Math.PI;
        var eastSpacing = long*Math.sin(componentAngle*pi/180)*Math.sin(sunDirectionAngle)/Math.tan(sunHeightAngle);
        return eastSpacing;
      },
      autocalComponentShadow: function(long,componentAngle) {
        var pi = Math.PI;
        var componentShadow = long*Math.cos(componentAngle*pi/180);
        return componentShadow;
      },
      autocalSumLong: function(frontSpacing,componentShadow) {
        var sumLong = parseFloat(frontSpacing) + parseFloat(componentShadow);
        return sumLong;
      },
      startUploadSurvery: function(projectId) {
        //upload图片
        angular.forEach(IMAGES.survey,function(imageClass){
          var imageCache = $imageUploadCache.getImagesByParams(projectId,'PROJECT',imageClass);
          // surveyImageClass[''+imageClass+''] = 'UPLOADING';
          if(imageCache.imageStatus == 'UPLOADED'){
            return ;
          }else if(imageCache.imageStatus == 'UPLOADING' && new Date().getTime() - imageCache.uploadStartTime < 1000 * 60 * 30){
            return ;
          }
          imageCache.funId = projectId ;
          imageCache.funName = 'PROJECT' ;
          imageCache.imageClass = imageClass ;
          imageCache.imageStatus = 'UPLOADING';
          //获取当前时间戳
          imageCache.uploadStartTime = new Date().getTime();
          $imageUploadCache.saveImages(imageCache);

          uploadImageToServer(projectId,'PROJECT',imageClass)
            .success(function(data){
              var imageCache = $imageUploadCache.getImagesByParams(projectId,'PROJECT',data.data.imageClass);
              imageCache.funId = projectId ;
              imageCache.funName = 'PROJECT' ;
              imageCache.imageClass = data.data.imageClass ;
              imageCache.imageStatus = 'UPLOADED';
              $imageUploadCache.saveImages(imageCache);
            }).error(function(data){
            var imageCache = $imageUploadCache.getImagesByParams(projectId,'PROJECT',data.data.imageClass);
            imageCache.funId = projectId ;
            imageCache.funName = 'PROJECT' ;
            imageCache.imageClass = data.data.imageClass ;
            imageCache.imageStatus = 'FAILED';
            $imageUploadCache.saveImages(imageCache);
          });
        })
      },
      startToUploadAll: function(){
        if($rootScope.networkState != Connection.WIFI){
          return ;
        }
        var imageCaches = $imageUploadCache.getImageWithStatus('SUBMIT');
        angular.forEach(imageCaches,function(imageCache){
          if(!imageCache.funId || !imageCache.funName || !imageCache.imageClass || !angular.isArray(imageCache.images) || imageCache.images.length == 0){
            return ;
          }

          if(imageCache.imageStatus == 'UPLOADED'){
            return ;
          }else if(imageCache.imageStatus == 'UPLOADING' && new Date().getTime() - imageCache.uploadStartTime < 1000 * 60 * 30){
            return ;
          }

          uploadImageToServer(imageCache.funId,imageCache.funName,imageCache.imageClass)
            .success(function(data){
              var imgCache = $imageUploadCache.getImagesByParams(data.data.funId,'PROJECT',data.data.imageClass);
              imgCache.funId = data.data.funId;
              imgCache.funName = 'PROJECT' ;
              imgCache.imageClass = data.data.imageClass ;
              imgCache.imageStatus = 'UPLOADED';
              $imageUploadCache.saveImages(imgCache);
            }).error(function(data){
            var imgCache = $imageUploadCache.getImagesByParams(data.data.funId,'PROJECT',data.data.imageClass);
            imgCache.funId = data.data.funId ;
            imgCache.funName = 'PROJECT' ;
            imgCache.imageClass = data.data.imageClass ;
            imgCache.imageStatus = 'FAILED';
            $imageUploadCache.saveImages(imgCache);
          });
        })
      },
      uploadImageToServer: uploadImageToServer,
      //保存网络图片
      saveNetworkImage: function(projectId,imageArray,imageClassArray){

      if(!angular.isArray(imageArray)){
        return ;
      }
      angular.forEach(imageArray,function(netImage){
        //获取key
          for(var key in netImage){

            if(angular.isArray(imageClassArray)){
              angular.forEach(imageClassArray,function(imageClass){
                if(imageClass != key){
                  return ;
                }else{
                  var keyImageList = netImage[''+key+''];

                  var imageCache = $imageUploadCache.getImagesByParams(projectId,'PROJECT',key);

                  imageCache.funId = projectId ;
                  imageCache.funName = 'PROJECT' ;
                  imageCache.imageClass = key ;

                  var imageList = [] ;
                  angular.forEach(keyImageList, function(image){
                    var cacheImage = {};
                    cacheImage.status = 'NEW';
                    cacheImage.imageUrl = image.middleImageUrl;
                    cacheImage.largeImageUrl = image.largeImageUrl;
                    cacheImage.smallImageUrl = image.smallImageUrl;
                    cacheImage.uuid = image.uuid ;
                    cacheImage.resource = 'NETWORK';
                    imageList.push(cacheImage);
                  });
                  imageCache.images = imageList ;
                  $imageUploadCache.saveImages(imageCache);
                }
              })
            }else{
              var keyImageList = netImage[''+key+''];

              var imageCache = $imageUploadCache.getImagesByParams(projectId,'PROJECT',key);

              imageCache.funId = projectId ;
              imageCache.funName = 'PROJECT' ;
              imageCache.imageClass = key ;
              //imageCache

              var imageList = [] ;
              angular.forEach(keyImageList, function(image){
                var cacheImage = {};
                cacheImage.status = 'NEW';
                cacheImage.imageUrl = image.middleImageUrl;
                cacheImage.largeImageUrl = image.largeImageUrl;
                cacheImage.smallImageUrl = image.smallImageUrl;
                cacheImage.uuid = image.uuid ;
                cacheImage.resource = 'NETWORK';
                imageList.push(cacheImage);
              });

              imageCache.images = imageList ;

              $imageUploadCache.saveImages(imageCache);
            }
          }
      });
    }
  };
});
